package m.html.list;

import m.html.element.Button;
import m.html.element.Element;
import m.html.element.Icon;
import m.html.element.Text;
import m.html.element.attr.ButtonType;
import m.html.element.attr.Size;
import m.system.util.StringUtil;

import java.util.*;

public class ListDropdown extends Button implements IListElement {
	
	public static ListDropdown primary(String title) {
		return new ListDropdown(Size.SMALL, ButtonType.PRIMARY,title);
	}
	public static ListDropdown success(String title) {
		return new ListDropdown(Size.SMALL,ButtonType.SUCCESS,title);
	}
	public static ListDropdown error(String title) {
		return new ListDropdown(Size.SMALL,ButtonType.ERROR,title);
	}
	public static ListDropdown link(String title) {
		return new ListDropdown(Size.SMALL,ButtonType.LINK,title);
	}
	public static ListDropdown ghost(String title) {
		return new ListDropdown(Size.SMALL,ButtonType.GHOST,title);
	}
	public static ListDropdown warn(String title) {
		return new ListDropdown(Size.SMALL,ButtonType.WARN,title);
	}
	public static ListDropdown def(String title) {
		return new ListDropdown(Size.SMALL,ButtonType.DEFAULT,title);
	}
	
	private ListDropdown(Size size,ButtonType type,String title) {
		super(size,type);
		super.E(new Text(title)).E(new Icon("icon-moreunfold"));
	}
	private final List<ListButton> btns= new ArrayList<>();
	public ListDropdown add(ListButton... button) {
		Collections.addAll(btns, button);
		return this;
	}
	@Override
	public ListEvent getEvent() {
		return null;
	}

	/**
	 * 获取参数所需的字段
	 * 
	 */
	public Set<String> getParamFields() {
		Set<String> pf= new HashSet<>();
		for(ListButton btn : btns) {
			pf.addAll(btn.getParamFields());
		}
		return pf;
	}
	private String getClassName(ButtonType type) {
		if(type==ButtonType.ERROR||type==ButtonType.GHOST_ERROR||type==ButtonType.LINK_ERROR) {
			return "ant-tag-error";
		}else if(type==ButtonType.PRIMARY||type==ButtonType.LINK) {
			return "ant-tag-processing";
		}else if(type==ButtonType.WARN) {
			return "ant-tag-warning";
		}
		return "";
	}
	@Override
	public String toString() {
		Element drop=Element.tag("a-dropdown");
		drop.E(new Text(super.toString()));
		Element menu=Element.tag("a-menu");
		for(int i=0;i<btns.size();i++) {
			ListButton btn=btns.get(i);
			Element ele=Element.tag("div").E(btn.getChilds());
			ele=btn.getEvent().toEventElement(ele,btn.getConfirm());
			Element mi=Element.tag("a-menu-item").A("key",String.valueOf(i)).A("class", getClassName(btn.getType())).E(ele);
			if(!StringUtil.isSpace(btn.getTest())) mi.A("v-if",btn.getTest());
			menu.E(mi);
		}
		drop.E(Element.tag("template ").A("#overlay").E(menu));
		return drop.toString();
	}

}
